package com.example.pictureManage.service.mainViewService;

import com.example.pictureManage.controller.ImageDetailController;
import com.example.pictureManage.service.mainViewService.imageBoxHelp.selectService;
import com.example.pictureManage.service.mainViewStage;
import com.example.pictureManage.util.FileUtil;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.concurrent.*;

//处理创建、加载图片的逻辑
public class imageBoxService {


    private final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(50,
            100,
            50,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );


    private final selectService selectServer = new selectService();



    public void createImageItem(Path imagePath, TilePane contentPane) {
        //在切换文件夹的时候清空缓存  缺点是删除了很多遍其实没必要删这么多次的
        selectServer.getMange()
                .getSelectVbox().clear();
        //为空白处建立监听器
        contentPane.addEventHandler(MouseEvent.MOUSE_CLICKED,e->{
            //左键点击空白处要删除所有    和普通的区分开来   点三次取消选中
            if (e.getButton() == MouseButton.PRIMARY && e.getClickCount() == 3){
                selectServer.getMange().ClearVBox();
                if(selectServer.getMMange().getContextMenu().isShowing()) {
                    selectServer.getMMange().getContextMenu().hide();
                }
                mainViewStage.getFileDetailLabel().setText("未选中图片");
            }
            else if (e.getButton() == MouseButton.SECONDARY){
                selectServer.RightClick(e);
            }
        });

        System.out.println(LocalDateTime.now());
        // 使用异步 加载图片并生成缩略图
        CompletableFuture<Image> thumbnailFuture = CompletableFuture.supplyAsync(() -> {
            //配置基础信息
            Image image = new Image(imagePath.toUri().toString(), 100, 100, true, false);
            ImageView imageView = new ImageView(image);
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(150);
            Label label = new Label(imagePath.getFileName().toString());
            label.setMaxWidth(150);
            label.setWrapText(true);

            return image;
        }, poolExecutor);
        System.out.println(LocalDateTime.now());

        thumbnailFuture.thenAcceptAsync(thumbnail -> {
            ImageView thumbnailView = new ImageView(thumbnail);
            Label label = new Label(imagePath.getFileName().toString());
            label.setMaxWidth(150);
            label.setWrapText(true);
            VBox vbox = new VBox(5, thumbnailView,label);
            vbox.setAlignment(Pos.CENTER);
            vbox.setSpacing(10);
            vbox.setPadding(new Insets(10));
            //放入路径参数方便操作
            vbox.setUserData(imagePath.toUri().toString());
            //设置鼠标左键
            //还要写SelectService业务处理
            vbox.addEventHandler(MouseEvent.MOUSE_CLICKED,event -> {
                // 双击打开图片
                if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2){
                    vbox.setStyle("-fx-background-color: none;");
                    openImageDetailWindow(getCachedImage((String) vbox.getUserData()));
                }
                //其他事情就归他管了
                selectServer.primaryClick(event,vbox);
            });

            Platform.runLater(() -> {
                //当前文件目录Path
                Path parentPath = mainViewStage.getFileNode().getFilePath();

                //子目录
                Path childPath;
                try {
                    URI uri = new URI((String) vbox.getUserData());
                    childPath = Paths.get(uri);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }

                //这里是避免中途切换目录导致异步加载   结果加载到不正确的地方
                if (!parentPath.relativize(childPath).toString().contains("..")){
                    contentPane.getChildren().add(vbox);
                }
            });

        }, ForkJoinPool.commonPool());

    }
    // 获取或加载图片的方法
    public static Image getCachedImage(String imageUrl) {
            // 加载图片并存储到缓存中
        return new Image(imageUrl);
    }
    // 打开新窗口的方法
    public void openImageDetailWindow(Image image) {
        try {
            Stage imageStage = new Stage();
            URL url = getClass().getResource("/com/example/pictureManage/image-detail-view.fxml");
            FXMLLoader loader = new FXMLLoader(url);
            VBox root = loader.load();

            ImageDetailController controller = loader.getController();
            //提前准备好stage
            imageStage.setScene(new Scene(root));

            //设置标题
            Path path = Paths.get(URI.create(image.getUrl()));
            imageStage.setTitle(FileUtil.getFileName(path));
            imageStage.show();
            controller.initialize(image, imageStage);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
